import { createDfuseClient } from '@dfuse/client'
import transfers from './transfers.js'
import mongoose from 'mongoose'
import fetch from 'node-fetch'
import ws from 'ws'
global.fetch = fetch
global.WebSocket = ws

if (process.env.NODE_ENV === 'prod') {
  mongoose.connect('mongodb://localhost:27017/fwmoniter')
}else{
  mongoose.connect('mongodb://localhost:27017/fwmoniter')
}

const db = mongoose.connection

const client = createDfuseClient({
  apiKey: 'b3ff420c4e3a353a55a77efe3efefc9b',
  network: 'wax.dfuse.eosnation.io',
})

db.once('open', function () {
  let Transfers = transfers()

  // // You must use a `$cursor` variable so stream starts back at last marked cursor on reconnect!
  const operation = `subscription($cursor: String!) {
  searchTransactionsForward(query:"receiver:farmerstoken action:transfers", cursor: $cursor) {
    undo cursor
    trace { id matchingActions { json } }
  }
}`

  async function main() {
    const stream = await client.graphql(operation, (message) => {
      if (message.type === 'data') {
        const {
          undo,
          cursor,
          trace: { id, matchingActions },
        } = message.data.searchTransactionsForward
        matchingActions.forEach(({ json: { from, to, quantities, memo } }) => {
          if (memo === 'withdraw' || memo === 'deposit') {
            console.log(`${id} ${from} -> ${to} ${memo} [${quantities}]${undo ? ' REVERTED' : ''}`)
            const object = {
              trx_id: id,
              timestamp: new Date().getTime(),
              from: from,
              to: to,
              memo: memo,
              FWF: 0,
              FWG: 0,
              FWW: 0
            }
            for (const coin of quantities) {
              const temparr = coin.split(' ')
              if (temparr && temparr.length > 0) {
                object[temparr[1].toUpperCase()] = parseFloat(temparr[0])
              }
            }
            // console.log(object);
            let tr = Transfers(object)
            tr.save((err) => {
              if (err) {
                console.log(err)
              }
            })
          }
        })

        // Mark stream at cursor location, on re-connect, we will start back at cursor
        stream.mark({ cursor })
      }

      if (message.type === 'error') {
        console.log('An error occurred', message.errors, message.terminal)
      }

      if (message.type === 'complete') {
        console.log('Completed')
      }
    })

    // Waits until the stream completes, or forever
    await stream.join()
    await client.release()
  }

  main().catch((error) => console.log('Unexpected error', error))
})
